<template>
  <div class="photo">
    <img :src="imgURL" alt="" ref="image" />
    <div class="footer">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="confirm" v-if="show">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserAvatar } from '@/api/user'
export default {
  name: 'Photo',
  components: {},
  props: {
    imgURL: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      cropper: null,
      show: true
    }
  },
  created() {
    this.show = true
  },
  mounted() {
    // 需要操作dom,放在mounted中
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      viewMode: 1, // 0可以拖出画布,1限制在画布中
      dragMode: 'move', // crop 鼠标拖出矩形裁剪模式,move拖动画布,none只能拖动剪裁窗口
      aspectRatio: 1, // 截图比例
      autoCropArea: 1, // 自动截取区域,1撑满窗口
      cropBoxMovable: false, // 剪裁窗口是否可以移动
      cropBoxResizable: false, // 截图区是否可以缩放
      background: false, // 是否显示背景
      movable: true // 默认为true,画布可移动
    })
  },
  activited() {},
  update() {},
  beforeRouteUpdate() {},
  methods: {
    confirm() {
      this.show = false
      this.cropper.getCroppedCanvas().toBlob(blob => {
        this.updateUserAvatar(blob)
      })
    },
    async updateUserAvatar(blob) {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '更新图片中'
      })
      try {
        // 发起请求,拿到数据 multipart/form-data 格式(文件,图片等) 要求Format对象
        const formData = new FormData()
        formData.append('photo', blob /*, 'example.png' */)
        // formData中已有键值对
        const { data } = await updateUserAvatar(formData)
        // console.log(data)
        // 添加loading
        // 更新视图
        this.$emit('updatePhoto', data.data.photo)
        // 关闭弹出层
        this.$emit('close')
        // 提示
        this.$toast.success('更新成功')
      } catch (error) {
        this.$toast.fail('更新失败')
      }
    }
  },
  filter: {},
  computed: {},
  watch: {}
}
</script>

<style lang="less" scoped>
.photo {
  height: 100%;
  background-color: #000;
  .footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .cancel,
    .confirm {
      padding: 15px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30px;
      color: #fff;
    }
  }
}
img {
  width: 100%;
}
</style>
